package com.willian.andrappfw.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.berwin.cocoadialog.CocoaDialog;
import com.willian.andrappfw.R;
import com.willian.andrappfw.network.RequestContext;
import com.willian.andrappfw.network.WRequest;
import com.willian.andrappfw.utils.ActivityStack;
import com.willian.andrappfw.utils.DialogUtils;
import com.willian.andrappfw.utils.OnClickedListener;
import com.willian.andrappfw.utils.Utils;

import java.io.Serializable;
import java.util.ArrayList;

public abstract class WBaseActivity extends FragmentActivity implements View.OnClickListener, RequestContext {
    private final ArrayList<WRequest> mRequestList = new ArrayList<>();
    CocoaDialog mLoadingDialog;
    private OnClickedListener onClickedListener;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        if (requestPermissions() != null && requestPermissions().length > 0) {
            ArrayList<String> notGrantedPermissionList = new ArrayList<>();
            for (String permission : requestPermissions()) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    notGrantedPermissionList.add(permission);
                }
            }
            if (notGrantedPermissionList.size() > 0) {
                String[] permissions = new String[notGrantedPermissionList.size()];
                notGrantedPermissionList.toArray(permissions);
                ActivityCompat.requestPermissions(this, permissions, 0);
                return;
            }
        }

        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void init() {
        if (requestLogin() && !Utils.isLogin()) {
            AlertDialog d = new AlertDialog.Builder(WBaseActivity.this, R.style.WAlertDialog)
                    .setTitle(R.string.please_login)
                    .setPositiveButton(R.string.login, (dialog, which) -> gotoLogin())
                    .setNegativeButton(R.string.cancel, (dialog, which) -> finish())
                    .setOnCancelListener(dialog -> finish())
                    .show();
            Utils.setAlertDialogButtonTextColor(d, R.color.blue_357CE9, R.color.blue_357CE9);
            return;
        }

        setContentView(getLayoutId());

//        View back = findViewById(R.id.back);
//        if (back != null) {
//            back.setOnClickListener(v -> onBackPressed());
//        }

//        SDTitleBar titleBar = findViewById(R.id.titleBar);
//        if (titleBar != null) {
//            titleBar.setBelowStatusBar();
//        }

        mLoadingDialog = DialogUtils.createLoadingDialog(this);

        ActivityStack.add(this);

        onClickedListener = new OnClickedListener() {
            @Override
            public void onClicked(View view) {
                WBaseActivity.this.onClicked(view);
            }
        };
        initView();
    }

    @Override
    public final void onClick(View v) {
        onClickedListener.onClicked(v);
    }

    public abstract void onClicked(View v);

    public abstract int getLayoutId();

    public abstract void initView();


    public <T> T getIntentSerializableValue(String key) {
        Intent intent = getIntent();
        if (intent == null) {
            return null;
        }
        Serializable s = intent.getSerializableExtra(key);
        if (s == null) {
            Parcelable p = intent.getParcelableExtra(key);
            if (p != null) {
                return (T) p;
            } else {
                return null;
            }
        } else {
            return (T) s;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.remove(this);
        cancelAllRequests();
    }

    @Override
    public void addRequest(WRequest wRequest) {
        mRequestList.add(wRequest);
    }

    @Override
    public void removeRequest(WRequest wRequest) {
        mRequestList.remove(wRequest);
    }

    @Override
    public void cancelAllRequests() {
        for (WRequest request : mRequestList) {
            request.cancel();
        }
    }

    public void setText(int viewId, CharSequence text) {
        TextView view = findViewById(viewId);
        if (view == null) {
            return;
        }
        view.setText(text);
    }

    public boolean requestLogin() {
        return false;
    }

    public void gotoLogin() {
        Intent intent = getIntent();
        //startActivity(new Intent(this, SDWelcomeActivity.class).putExtra(SDIntentKeys.INTENT_KEY_0, intent));
        finish();
    }

    String[] requestPermissions() {
        return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            init();
        } else {
            AlertDialog d = new AlertDialog.Builder(this, R.style.WAlertDialog).setTitle(R.string.permission_not_granted).
                    setPositiveButton(R.string.setting, (dialog, which) -> {
                        Intent localIntent = new Intent();
                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(localIntent);
                        finish();
                    }).setNegativeButton(R.string.cancel, (dialog, which) -> finish()).show();
            Utils.setAlertDialogButtonTextColor(d, R.color.blue_357CE9, R.color.blue_357CE9);
        }
    }
}
